import uuid
import time
import hashlib
import base64
import requests

""" 
企业微信告警生成
"""
# 函数用法：生成一组唯一的鉴权请求头参数
def param(token):
    Authorization = token
    nonce = str(uuid.uuid4())
    timestamp = str(int(time.time() * 1000))

    data_to_hash = f"Authorization={Authorization}&nonce={nonce}&timestamp={timestamp}"

    try:
        md = hashlib.sha256()
        md.update(data_to_hash.encode('utf-8'))
        md5 = md.digest()
        sign = base64.urlsafe_b64encode(md5).rstrip(b'=').decode('utf-8')

    except Exception as e:
        print("Error:", e)

    return Authorization, nonce, timestamp, sign


# 函数用法：请求API，并返回结果
def get_alerts(url, params, headers):
    response = requests.get(url=url, params=params, headers=headers)

    if response.status_code == 200:
        return response.json()  # 假设API返回的是JSON格式的数据
    else:
        return response.status_code


# 函数用法：对告警信息按城市代码分类
def classify_alerts(alerts):
    classified = {}
    for alert in alerts:
        city_code = alert['city_code']
        if city_code not in classified:
            classified[city_code] = []
        classified[city_code].append(alert)
    return classified


# 函数用法：解析告警信息
def build_message(alerts):
    message = "# 告警通知\n"
    for alert in alerts:
        # 可以自定义设置推送告警的信息
        message += (f">告警发生时间：<font color=\"comment\">{alert['eventtime']}</font>\n"
                    f">区县：<font color=\"comment\">{alert['dx_district_name']}</font>\n"
                    f">告警标题：<font color=\"warning\">{alert['alarmtitle']}</font>\n"
                    f">厂商：<font color=\"comment\">{alert['vendor']}</font>\n"
                    f">基站小区：<font color=\"comment\">{alert['nodeb_name']}-{alert['cell_name']}</font>\n\n")
    return message


# 推送告警信息到企业微信机器人
def send_to_dingtalk(webhook_url, message):
    headers = {'Content-Type': 'application/json'}
    payload = {'msgtype': 'markdown', 'markdown': {'content': message}}
    # print(payload)
    response = requests.post(webhook_url, headers=headers, json=payload)
    if response.status_code == 200:
        print("消息发送成功")
    else:
        print(f"消息发送失败: {response.text}")


if __name__ == "__main__":
    # 企业微信机器人的webhook地址
    webhook_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=22cad3f9-77b3-486e-987e-38945b54f915'
    # 设置请求URL
    url = 'http://134.225.144.80:7491/opensharex/api/tenants/dtsw_js/fact_alarm_filtered_log_5min'
    # 设置共享用户关联令牌
    token = "io2zj639PrAcMOo6jaUWJ"
    # 设置请求参数
    p_province = '360000'
    p_date = '2024-11-13'
    p_hour = '1'
    p_5min = '6'
    eSerialNum = ''
    apiType = 'blocking'

    # 设置查询参数
    params = {'p_province': p_province, 'p_date': p_date, 'p_hour': p_hour, 'p_5min': p_5min, 'eSerialNum': eSerialNum,
              'apiType': apiType}

    # 调用函数获取四个鉴权请求头参数
    Authorization, nonce, timestamp, sign = param(token)
    # 设置请求头
    headers = {'Authorization': Authorization, 'timestamp': timestamp, 'sign': sign, 'nonce': nonce, }

    # 调用函数请求API，并返回告警信息
    alerts = get_alerts(url, params, headers)
    # 分类告警信息
    classified_alerts = classify_alerts(alerts)

    # 发送告警信息
    for city_code, alerts in classified_alerts.items():
        message = build_message(alerts)
        send_to_dingtalk(webhook_url, message)
